package com.csx.governance.traffic.adapter.outbound.webclient;

import com.csx.governance.traffic.core.TransportableAttributes;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.Map;

/**
 * <p>WebClient.Builder的后置处理器</p>
 * <p>主要将需要透传给外调请求的属性(包含swimLaneId)放入到外调请求的请求头中,该类是针对 WebClient 的支持</p>
 * <p>之所以要在此处做透传是因为WebClient的header一旦诶构建不能被修改，因此需要通过该扩展点透传</p>
 * @author cuisongxu
 * @date 2023/4/12 22:12
 */
public class TrafficWebClientBuilderBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

        if(bean instanceof WebClient.Builder) {
            WebClient.Builder builder = (WebClient.Builder) bean;
            // 添加回调,将需要透传的属性设置进外调请求的header中,swimLaneId泳道就是在此处的回调中放入到外调请求中,该回调会在外调前调用
            builder.defaultRequest(requestHeadersSpec -> {
                Map<String, String> attributes = TransportableAttributes.getAttributes();
                attributes.forEach(requestHeadersSpec::header);
            });
            return builder;
        }
        return bean;
    }
}
